<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="检查表名称" v-bind="validateInfos.name">
	          <j-dict-select-tag v-model:value="formData.name" dictCode="tb_base_check,name,id" placeholder="请选择检查表名称" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查标准类型" v-bind="validateInfos.inspectionStandardType">
	          <j-dict-select-tag v-model:value="formData.inspectionStandardType" dictCode="inspectionStandardType" placeholder="请选择检查标准类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查目的" v-bind="validateInfos.aim">
	          <a-textarea v-model:value="formData.aim" :rows="4" placeholder="请输入检查目的" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="检查要求" v-bind="validateInfos.demand">
	          <a-textarea v-model:value="formData.demand" :rows="4" placeholder="请输入检查要求" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="附件" v-bind="validateInfos.attachments">
	          <j-upload v-model:value="formData.attachments"  :disabled="disabled" ></j-upload>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="是否删除" v-bind="validateInfos.deleted">
            <j-dict-select-tag type='radio' v-model:value="formData.deleted" dictCode="yn" placeholder="请选择是否删除" :disabled="disabled"/>
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="检查项" key="tbBaseCheckItem" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbBaseCheckItemTableRef"
          :loading="tbBaseCheckItemTable.loading"
          :columns="tbBaseCheckItemTable.columns"
          :dataSource="tbBaseCheckItemTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTbBaseCheckItemListByMainId, queryDataById, saveOrUpdate } from '../TbBaseCheck.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tbBaseCheckItemColumns} from '../TbBaseCheck.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TbBaseCheckForm",
    components:{
      JDictSelectTag,
      JUpload,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tbBaseCheckItemTableRef = ref();
      const tbBaseCheckItemTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbBaseCheckItemColumns,
        dataSource: []
      });
      const activeKey = ref('tbBaseCheckItem');
      const formData = reactive<Record<string, any>>({
        id: '',
        name: '',   
        inspectionStandardType: '',   
        aim: '',   
        demand: '',   
        attachments: '',   
        deleted: '',   
      });

      //表单验证
      const validatorRules = reactive({
        name: [{ required: true, message: '请输入检查表名称!'},],
        inspectionStandardType: [{ required: true, message: '请输入检查标准类型!'},],
        aim: [{ required: true, message: '请输入检查目的!'},],
        demand: [{ required: true, message: '请输入检查要求!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: true});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        tbBaseCheckItemTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tbBaseCheckItemDataList = await queryTbBaseCheckItemListByMainId(row['id']);
        tbBaseCheckItemTable.dataSource = [...tbBaseCheckItemDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        Object.keys(row).map(k => {
          formData[k] = row[k];
        });
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tbBaseCheckItem': tbBaseCheckItemTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        tbBaseCheckItemTableRef,
        tbBaseCheckItemTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>
